package com.vnaloha.common.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vnaloha.common.dao.UserDAO;
import com.vnaloha.common.model.User;
import com.vnaloha.util.EncryptUtil;
import com.vnaloha.util.StringUtil;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDAO userDAO;

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.UserService#addUser(com.vnaloha.common.model.User)
	 */
	@Override
	@Transactional
	public void addUser(User user) {
		int lenghtSalt = 10;
		// set encrypt password
		String salt = StringUtil.randomString(lenghtSalt);
		String password = EncryptUtil.encryptSHA1(user.getPassword(), salt); 
		// set new password and salt to object user
		user.setPassword(password);
		user.setSalt(salt);
		// add new user
		userDAO.addUser(user);
	}

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.UserService#listUser()
	 */
	@Override
	@Transactional
	public List<User> listUser() {
		return userDAO.listUser();
	}

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.UserService#removeUser(java.lang.Integer)
	 */
	@Override
	@Transactional
	public void removeUser(Integer id) {
		userDAO.removeUser(id);
	}

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.UserService#getById(java.lang.Integer)
	 */
	@Override
	@Transactional
	public User getById(Integer id) {
		return userDAO.getById(id);
	}

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.service.UserService#update(com.vnaloha.common.model.User)
	 */
	@Override
	public void update(User user) {
		User user2 = userDAO.getById(user.getId());
		String currentPassword = EncryptUtil.encryptSHA1(user.getPassword(), user.getSalt());
		if(currentPassword == user2.getPassword()) {
			userDAO.update(user);	
		}
	}

}
